package ti.me.seek2chat.utilities

import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import ti.me.seek2chat.R
import ti.me.seek2chat.activities.ChatActivity
import ti.me.seek2chat.models.ChatMessage

/**
 * NotificationService 是一个用于处理通知的服务类。
 * 它负责创建通知渠道、发送通知以及检查和请求通知权限。
 *
 * @property context 上下文对象，用于访问系统服务和资源。
 */
class NotificationService(private val context: Context) {
    companion object {
        const val REQUEST_CODE_NOTIFICATION_PERMISSION = 1001
    }

    /**
     * 发送通知的方法。
     * 当接收到新的聊天消息时，调用此方法发送通知。
     *
     * @param chatMessage 聊天消息对象，包含消息的详细信息。
     */
    fun sendNotification(chatMessage: ChatMessage) {
        if (checkNotificationPermission()) {
            val channelId = "chat_message_channel"
            val channelName = "Chat Messages"
            val notificationId = 1

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val importance = NotificationManager.IMPORTANCE_HIGH
                val channel = NotificationChannel(channelId, channelName, importance)
                val notificationManager: NotificationManager =
                    context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(channel)
            }

            val intent = Intent(context, ChatActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
                putExtra(Constants.KEY_USER, chatMessage.senderId)
            }
            val pendingIntent: PendingIntent = PendingIntent.getActivity(
                context,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )

            val builder = NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("新消息来自 ${chatMessage.conversionName}")
                .setContentText(chatMessage.message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)

            with(NotificationManagerCompat.from(context)) {
                notify(notificationId, builder.build())
            }
        } else {
            requestNotificationPermission()
        }
    }

    /**
     * 检查通知权限的方法。
     * 检查应用是否具有发送通知的权限。
     *
     * @return 如果具有通知权限，则返回 true；否则返回 false。
     */
    private fun checkNotificationPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.checkSelfPermission(
                context,
                android.Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        } else true
    }

    /**
     * 请求通知权限的方法。
     * 如果应用没有通知权限，则请求用户授予通知权限。
     */
    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (context is Activity) {
                ActivityCompat.requestPermissions(
                    context,
                    arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
                    REQUEST_CODE_NOTIFICATION_PERMISSION
                )
            } else {
                Log.e(
                    "NotificationService",
                    "Context is not an Activity, cannot request notification permission"
                )
            }
        }
    }
}